package org.btik.lightweb.msg;

import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.context.thread.SystemControlAble;
import org.btik.lightweb.client.WebSockControl;
import org.btik.light.meta.base.Report;
import org.btik.light.meta.event.DevReportEventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.LinkedBlockingQueue;

@Service
public class DevReportHandler extends Thread implements DevReportEventHandler, SystemControlAble {

    private static final Log LOG = LogFactory.getLog(DevReportHandler.class);

    private boolean isRunning;

    private final LinkedBlockingQueue<Report> reportQueue = new LinkedBlockingQueue<>();

    private final Gson gson = new Gson();

    @Autowired
    private WebSockControl webSockControl;

    @Override
    public void onMessage(Report report) {
        reportQueue.add(report);
    }

    @Override
    public void restart() {

    }

    @Override
    public void shutdown(String msg) {
        isRunning = false;
    }



    @Override
    public void run() {

        while (isRunning) {
            try {
                Report take = reportQueue.take();
                webSockControl.sendAll(gson.toJson(take));
            } catch (InterruptedException e) {
                LOG.error("", e);
            }

        }
    }
}
